package org.example.wu_and_dian.service.impl;

import java.sql.SQLIntegrityConstraintViolationException;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.wu_and_dian.constant.HttpStatus;
import org.example.wu_and_dian.dto.request.RegisterDto;
import org.example.wu_and_dian.dto.response.AjaxResult;
import org.example.wu_and_dian.entity.User;
import org.example.wu_and_dian.mapper.UserMapper;
import org.example.wu_and_dian.service.RegisterService;
import org.example.wu_and_dian.utils.PasswordUtil;
import org.example.wu_and_dian.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;

@Service
public class RegisterServiceImpl extends ServiceImpl<UserMapper, User> implements RegisterService {
    @Autowired
    private UserMapper userMapper;


    @Override
    public AjaxResult register(RegisterDto registerDto) {
        // 验证邮箱格式是否符合163邮箱或QQ邮箱规则
        if (!isValidEmail(registerDto.getEmail())) {
            return AjaxResult.error(HttpStatus.BAD_REQUEST, "邮箱格式不正确，请使用163邮箱或QQ邮箱");
        }

        // 检查邮箱是否已存在
        User existingUser = userMapper.selectUserByEmail(registerDto.getEmail());
        if (existingUser != null) {
            return AjaxResult.error(HttpStatus.BAD_REQUEST, "该邮箱已被注册");
        }

        // 创建新用户并加密密码
        User newUser = new User();
        newUser.setId(IdWorker.getId());
        newUser.setEmail(registerDto.getEmail());
        newUser.setPassword(registerDto.getPassword()); // 直接使用前端传入的MD5加密值
        try {
            userMapper.insertUser(newUser);
        } catch (DataIntegrityViolationException dive) {
            log.error("数据库完整性校验失败：" + dive.getMessage());
            if (dive.getCause() instanceof SQLIntegrityConstraintViolationException) {
                SQLIntegrityConstraintViolationException ex = (SQLIntegrityConstraintViolationException) dive.getCause();
                if (ex.getErrorCode() == 1062) { // MySQL唯一约束错误代码
                    return AjaxResult.error(HttpStatus.BAD_REQUEST, "邮箱已被注册");
                }
            }
            return AjaxResult.error(HttpStatus.ERROR, "注册失败，请检查输入数据");
        } catch (Exception e) {
            log.error("注册过程中发生未知异常：" + e.getMessage());
            return AjaxResult.error(HttpStatus.ERROR, "系统错误，请稍后重试");
        }

        return AjaxResult.success(HttpStatus.SUCCESS, "注册成功");
    }

    // 添加邮箱格式验证方法
    private boolean isValidEmail(String email) {
        return email.matches("[a-zA-Z0-9._%+-]+@(163|qq)\\.com");
    }

}